package com.lmr.boot.controller;

import com.lmr.boot.bean.Account;
import com.lmr.boot.bean.City;
import com.lmr.boot.bean.User;
import com.lmr.boot.service.AccountService;
import com.lmr.boot.service.CityService;
import com.lmr.boot.service.impl.AccountServiceImpl;

import com.lmr.boot.service.impl.CityServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@Log4j2
public class IndexController {



    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    AccountService accountService;

    @Autowired
    CityService cityService;


    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @ResponseBody
    @PostMapping("/city1")

    public City saveCity(City city){
        cityService.saveCity(city);
        return city;
    }




    @ResponseBody
    @GetMapping("/city")
    public City getByIdcity(Long id){
        City byId = cityService.getById(id);
        return  byId;
    }



    @ResponseBody
    @GetMapping("/acct")
    public Account getById(Integer id){
        Account acctById = accountService.getAcctById(id);
        return acctById;
    }
    @ResponseBody
    @GetMapping("/sql")
    public String query(){
        Long aLong = jdbcTemplate.queryForObject("select count(*) from user_role", Long.class);
        System.out.println(aLong);
        return aLong+"";
    }
    /**
     * 登录页
     * @return
     */
    @GetMapping({"/","/login"})
    public String loginPage(){
        return "login";
    }


    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model){
        System.out.println(user);
        if(user.getUserName().equals("123")&&user.getPassword().equals("123")){
            session.setAttribute("loginUser",user);
            return "redirect:/index.html";  //如果不用重定向每次刷新页面其实都是重新提交表单，麻烦。
        }else {
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    /**
     * 防止重新提交表单，这样才是真正进入index页面，
     * @return
     */
    @GetMapping("/index.html")
    public String mainPage(HttpSession session,Model model){


        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String s = operations.get("/index.html");
        String s1 = operations.get("/sql");
        model.addAttribute("maincount",s);
        model.addAttribute("sqlCount",s1);


        return  "index";
        //是否登录,拦截器，过滤器

    }

}
